var EXPORTED_SYMBOLS = ["storeOpenIdImage"];

Components.utils.import("resource://gre/modules/Services.jsm");

function storeOpenIdImage(OpenIdStorage, realm, claimed_id, image, callback) {
  try {
    if (!OpenIdStorage) {
      OpenIdStorage = Components.classes['@openinfocard.com/openidstorage;1'].getService().wrappedJSObject;
    }
    var consoleService = Services.console;
    consoleService.logStringMessage("image.src = " + image.getAttribute("src"));
    var dataUrl;
    var AppShellService = Components.classes["@mozilla.org/appshell/appShellService;1"]
        .getService(Components.interfaces.nsIAppShellService);
    var canvas = AppShellService.hiddenDOMWindow.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
    var hiddenImage = AppShellService.hiddenDOMWindow.document.createElementNS("http://www.w3.org/1999/xhtml", "img");
    // hiddenImage.width = "16";
    // hiddenImage.height = "16";
    hiddenImage.onload = function() {
      consoleService.logStringMessage("width=" + this.width + " height=" + this.height);
      canvas.width = this.width;
      canvas.height = this.height;
      var context = canvas.getContext('2d');
      context.drawImage(this, 0, 0);
      dataUrl = canvas.toDataURL();
      consoleService.logStringMessage("storeOpenIdImage dataUrl = " + dataUrl);
      OpenIdStorage.setImage(claimed_id, realm, dataUrl);
      if (typeof(callback) == "function") {
        callback(dataUrl);
      }
      // var xx = OpenIdStorage.getImage(claimed_id, realm);
      // consoleService.logStringMessage("xx = " + xx);
    };
    hiddenImage.src = image.getAttribute("src");
  } catch (e) {
    Components.utils.reportError(e);
  }
}